package com.example.dhhyc.demos.filter;

/**
 * Describe :
 * question :
 *
 * @author BaiShanshan
 * @date 2024/6/18 11:14
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 过滤器拦截请求，实现加密解密功能
 *
 * @Component 将此Filter交给Spring容器管理
 * @WebFilter 通过WebFilter进行Filter声明，这样容器在进行部署的时候就会处理该Filter
 *
 */
@Component
public class EncryptFilter implements Filter {
    Logger log = LoggerFactory.getLogger(this.getClass());
    @Value("${admin.encrypt.excludeUrl}")
    private String ignoreStr;
    private String[] ignoreArr;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }
    /**
     * 有错误相应返回-44
     *
     * @param response
     * @throws IOException
     */
    private void getFailResponse(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        out = response.getWriter();
//        out.write("{\n" +
//                "    \"status\":"+ Constant.ENCRYPT_FAIL +",\n" +
//                "    \"message\": null,\n" +
//                "    \"data\": []\n" +
//                "}");
        //加密后的错误消息
        out.write("+D+JO8tuwkrNbxnTTLdqStifmQceT+LlYETnIG/JZKrbAn+gIiqIp3VbzBV1y6R8B7aY53VM2xHa7cY3Osbnqw==");
        out.flush();
        out.close();
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        if(ignoreArr==null){
            ignoreArr = ignoreStr.split(",");
        }
        HttpServletRequest HttpRequest=(HttpServletRequest)request;
        HttpServletResponse HttpResponse=(HttpServletResponse)response;
        boolean flag=isIgnore(HttpRequest,ignoreArr);
        if(flag) {
            try {
                chain.doFilter(HttpRequest, HttpResponse);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }else{
            try{
                //响应处理  包装响应对象 res 并缓存响应数据
                ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
                //执行业务逻辑 交给下一个过滤器或servlet处理
                chain.doFilter(request, responseWrapper);
                byte[] resData = responseWrapper.getResponseData();
                //设置响应内容格式，防止解析响应内容时出错
//            responseWrapper.setContentType("text/plain;charset=UTF-8");
                //加密响应报文并响应
//                String encryptBASE64 = AesEncryptUtils.encrypt(new String(resData), "Constant.ENCRYPT_STR");
                String encryptBASE64 = AesEncryptUtils.encrypt(new String(resData), "Constant.ENCRYPT");
                PrintWriter out = response.getWriter();
                out.print(encryptBASE64);
                out.flush();
                out.close();

            }catch(Exception e){
                try {
                    getFailResponse((HttpServletResponse)response);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * 哪些路径不处理
     * @param request
     * @param strArr
     * @return
     */
    public boolean isIgnore(HttpServletRequest request, String[] strArr) {
        String path=request.getRequestURI();
        for(String ignore:strArr) {
            if(path.contains(ignore)) {
                return true;
            }
        }
        return false;
    }
}

